package DAO.impl.hibernate;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import domain.Message;
import DAO.IMessageDAO;

@Transactional
@Component
public class MessagesDaoImpl implements IMessageDAO {

	@SuppressWarnings("unused")
	private static Logger log = Logger.getLogger(MessagesDaoImpl.class);
	private SessionFactory sessionFactory;
		
	public MessagesDaoImpl() {}
	
	public MessagesDaoImpl(SessionFactory sessionFactory) {
		super();
		this.sessionFactory = sessionFactory;
	}

	@Override
	public int createMessage(Message message) {		
		sessionFactory.getCurrentSession().saveOrUpdate(message);					
		return 0;			
	}

	@Override
	public int updateMessage(Message message) {		
		return createMessage(message);
	}

	@Override
	public int deleteMessage(int id) {		
		Message message = getMessage(id);			
		return deleteMessage(message);			
	}
	
	public int deleteMessage(Message message) {
		int result = -1;
		if (message != null) {
			sessionFactory.getCurrentSession().delete(message);
			result = 0;
		}					
		return result;			
	}

	@Override
	public Message getMessage(int id) {		
		return (Message)sessionFactory.getCurrentSession().get(Message.class, id);			
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Message> getAllMessages() {		
		Session session = sessionFactory.getCurrentSession();			
		List<Message> messages = session.createQuery("from Message").list();
		return messages;		
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}	
}
